package org.mitoma.logger.client;

import org.mitoma.logger.shared.AuthInfo;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratedPopupPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class LoginPanel extends Composite {

  private static LoginPanelUiBinder uiBinder = GWT
                                                 .create(LoginPanelUiBinder.class);

  interface LoginPanelUiBinder extends UiBinder<Widget, LoginPanel> {
  }

  @UiField
  TextBox         email;
  @UiField
  PasswordTextBox password;
  @UiField
  Button          login;

  public LoginPanel() {
    initWidget(uiBinder.createAndBindUi(this));
  }

  @UiHandler("login")
  void login(ClickEvent event) {
    GlobalRepository.getService().login(email.getText(), password.getText(),
        new AsyncCallback<AuthInfo>() {

          @Override
          public void onFailure(Throwable caught) {
            PopupPanel pp = new DecoratedPopupPanel(true, true);
            pp.setGlassEnabled(true);
            pp.add(new Label("ログインに失敗しました。"));
            pp.showRelativeTo(login);
          }

          @Override
          public void onSuccess(AuthInfo info) {
            GlobalRepository.setAuthInfo(info);
            GlobalRepository.moveToTop();
          }
        });
  }
}
